package homework.shiwu;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class TransactionContext {
    private Map<Account, Double> savedStates = new HashMap<>();

    // 保存账户状态
    public void saveState(Account account) {
        savedStates.put(account, account.getBalance());
    }

    // 回滚所有保存的状态
    public void rollback() {
        savedStates.forEach((account, savedBalance) -> {
            try {
                // 获取私有字段
                Field balanceField = Account.class.getDeclaredField("balance");
                // 设置可访问
                balanceField.setAccessible(true);
                // 通过反射设置字段值
                balanceField.set(account, savedBalance);
                System.out.println("回滚账户 " + account.getAccountNumber() + " 到余额: " + savedBalance);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
                System.err.println("回滚失败: " + e.getMessage());
            }
        });
        // 清空保存的状态
        savedStates.clear();
    }


    // 提交事务（清除保存的状态）
    public void commit() {
        savedStates.clear();
    }
}
